package com.yupi.springbootinit.controller;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:
 * User:Mr.Du
 * Date:2023/7/7
 * Time:23:31
 */
@RestController("/thread")
@Slf4j
public class TestThreadController {


    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/add")
    public void add(String name){
        CompletableFuture.runAsync(() -> {
            log.info("任务执行中，" + name);
            try{
                Thread.sleep(600000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }, threadPoolExecutor);
    }

    @GetMapping("/get")
    public String get(){
        Map<String,Object> mp = new HashMap<>();
        int size = threadPoolExecutor.getQueue().size();
        mp.put("队列长度：", size);
        long taskCount = threadPoolExecutor.getTaskCount();
        mp.put("任务总数：", taskCount);
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        mp.put("已完成任务数：", completedTaskCount);
        int activeCount = threadPoolExecutor.getActiveCount();
        mp.put("正在工作的线程数：", activeCount);
        return JSONUtil.toJsonStr(mp);
    }
}
